package frame

import (
	"github.com/gin-gonic/gin"
)

type HandlerFunc = func(*Webline)

type WebEngine struct {
	RouterGroup
}

func (this *WebEngine) Engine() *gin.Engine {
	return this.eg
}

type RouterGroup struct {
	server *Server
	eg     *gin.Engine
	grp    *gin.RouterGroup
}

func (this *RouterGroup) route() gin.IRoutes {
	if this.grp != nil {
		return this.grp
	}
	return this.eg
}

// GET请求
func (this *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) *Router {
	r := &Router{server: this.server}
	this.route().GET(relativePath, r.wareFunc(handlers)...)
	return r
}

func (this *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) *Router {
	r := &Router{server: this.server}
	this.route().POST(relativePath, r.wareFunc(handlers)...)
	return r
}

func (this *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) *Router {
	r := &Router{server: this.server}
	this.route().PUT(relativePath, r.wareFunc(handlers)...)
	return r
}

func (this *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) *Router {
	r := &Router{server: this.server}
	this.route().DELETE(relativePath, r.wareFunc(handlers)...)
	return r
}

func (this *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) *Router {
	r := &Router{server: this.server}
	this.route().Any(relativePath, r.wareFunc(handlers)...)
	return r
}

func (this *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
	r := &Router{server: this.server}
	var grp *gin.RouterGroup
	if this.grp != nil {
		grp = this.grp.Group(relativePath, r.wareFunc(handlers)...)
	} else {
		grp = this.eg.Group(relativePath, r.wareFunc(handlers)...)
	}
	return &RouterGroup{grp: grp, server: this.server}
}

// 权限配置使用
func (this *RouterGroup) Permission(name string, code ...string) *RouterGroup {
	this.server.permission.add(name, code...)
	return this
}

func (this *RouterGroup) Use(middleware ...HandlerFunc) {
	r := &Router{server: this.server}
	this.route().Use(r.wareFunc(middleware)...)
}

type Router struct {
	server         *Server
	handlers       []HandlerFunc
	permissionCode string
	permissionName string
}

// 权限配置使用
func (this *Router) Permission(name string, codes ...string) {
	if len(codes) == 1 {
		this.permissionCode = codes[0]
	}
	this.permissionName = name
	this.server.permission.add(name, codes...)
}

func (this *Router) wareFunc(handlers []HandlerFunc) []gin.HandlerFunc {
	fns := make([]gin.HandlerFunc, 0)
	for _, handler := range handlers {
		fns = append(fns, func(c *gin.Context) {
			webline := newWebline(c, this.server)
			webline.routerName = this.permissionName
			if this.permissionCode != "" {
				this.server.app.CheckPermission(webline, this.permissionCode, this.permissionName)
			}
			webline.Set("ROUTER_NAME", this.permissionName)
			handler(webline)
		})
	}
	return fns
}
